package com.gupao.study.delegate;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class DispatcherServlet extends HttpServlet {
    public DispatcherServlet() {
        super();
    }

    Map<String, Method> ioc = new HashMap<String, Method>();

    @Override
    public void init() throws ServletException {
        try {
            ioc.put("hello",HelloController.class.getMethod("hello"));
            ioc.put("test",TestController.class.getMethod("test"));
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        super.init();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String url = req.getRequestURI();
        if(ioc.containsKey(url)){
            try {
                ioc.get(url).invoke(ioc.get(url).getClass().newInstance());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
